import { API, request } from "./request";
import { fetchUserInfo } from "./user";

export const appleLogin = (callback) => {
  uni.login({
    provider: "apple",
    success: function (loginRes) {
      uni.getUserInfo({
        provider: "apple",
        success: function (info) {
          console.log("apple login info: ", loginRes, info);
          fetchAppleToken(info.userInfo.openId, info.userInfo.identityToken, callback);
        },
      });
    },
    fail: function (err) {
      uni.showToast({ title: "登录失败:" + err.code, icon: "error" });
      if (callback) {
        callback();
      }
    },
  });
};

function logout(type, calback) {
  plus.oauth.getServices(
    function (services) {
      for (var i in services) {
        console.log("html5 plus service list: ", services[i]);
        if (services[i].id === type) {
          console.log("html5 plus service logout: ", services[i]);
          services[i].logout(
            function (e) {
              plus.nativeUI.alert("注销登录认证成功!");
            },
            function (e) {
              plus.nativeUI.alert("注销登录认证失败: " + JSON.stringify(e));
            }
          );
        }
      }
    },
    function (e) {
      plus.nativeUI.alert("获取登录鉴权服务列表失败：" + JSON.stringify(e));
    }
  );
}

export const appleRegister = (appleOpenId, appleIdenityToken, mobile, verifyCode, callback) => {
  request({
    path: API.LOGIN_APPLE_LOGIN,
    params: {
      user: appleOpenId,
      identity_token: appleIdenityToken,
      user_phone: mobile,
      code: verifyCode,
    },
  }).then((data) => {
    if (data.isSuccess) {
      uni.setStorageSync("token", data.data.token);
      fetchUserInfo(callback);
    } else {
      logout("apple");
      if (callback) {
        callback();
      }
    }
  });
};

function fetchAppleToken(openId, identityToken, callback) {
  request({
    path: API.APPLE_FETCH_TOKEN,
    params: {
      user: openId,
      identity_token: identityToken,
    },
  }).then((data) => {
    if (data.isSuccess) {
      if (!data.data || data.data.token === "") {
        uni.navigateTo({
          url: "/pages/bind-mobile/index?bindType=apple&appleOpenId=" + openId + "&appleIdenityToken=" + identityToken,
        });
      } else {
        uni.setStorageSync("token", data.data.token);
        fetchUserInfo(callback);
      }
    } else {
      if (callback) {
        callback();
      }
    }
  });
}

export const wechatLogin = (callback) => {
  uni.login({
    provider: "weixin",
    onlyAuthorize: true,
    success: function (event) {
      fetchWechatToken(event.code, callback);
    },
    fail: function (res) {
      console.log("fail:", res);
      if (callback) {
        callback();
      }
    },
  });
};

export const wechatRegister = (appCode, userPhone, verifyCode, callback) => {
  request({
    path: API.LOGIN_WXAPP_LOGIN,
    params: {
      app_code: appCode,
      user_phone: userPhone,
      code: verifyCode,
    },
  }).then((data) => {
    if (data.isSuccess) {
      uni.setStorageSync("token", data.data.token);
      fetchUserInfo(callback);
    } else {
      logout("weixin");
      if (callback) {
        callback();
      }
    }
  });
};

function fetchWechatToken(appCode, callback) {
  request({
    path: API.LOGIN_WXAPP_FETCH_TOKEN,
    params: { app_code: appCode },
  }).then((data) => {
    if (data.isSuccess) {
      if (data.data.token === "") {
        uni.navigateTo({
          url: "/pages/bind-mobile/index?bindType=wechat&appCode=" + appCode,
        });
      } else {
        uni.setStorageSync("token", data.data.token);
        fetchUserInfo(callback);
      }
    } else {
      if (callback) {
        callback();
      }
    }
  });
}
